package com.mycompany.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.mycompany.entity.Bill;
import com.mycompany.entity.Number;
import com.mycompany.entity.Rule;
import com.mycompany.service.BillService;
import com.mycompany.service.NumberService;
import com.mycompany.service.RuleService;
import com.mycompany.unity.NumberUnity;

/**
 * Handles requests for the application home page.
 */
@Controller
public class BillController {
	
	private static final Logger logger = LoggerFactory.getLogger(BillController.class);
	
	@Autowired
	BillService billService; 
	
	@Autowired
	NumberService numberService;
	
	@Autowired
	RuleService ruleService; 
	
	
	DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
	
	@RequestMapping(value = "/admin/bill", method = RequestMethod.GET)
	public String billListHandle(Model model) {
		logger.debug("Bill List here!");
		List<Bill> bills = billService.findAll();
		model.addAttribute("bills", bills);
		return "admin/bill/bill_list";
	}
	@RequestMapping(value = "/admin/billSearch")
	public String billFindHandle(Model model,@RequestParam(value = "name") String name) {
		logger.debug("billFindHandle here!");
		Bill u = new Bill();
		u.setName(name);
		List<Bill> bills = billService.findListByCodition(u);
		model.addAttribute("bills", bills);
		return "admin/bill/bill_list";
	}
	@RequestMapping(value = "/admin/billDelete")
	public String billDeleteHandle(Model model,@RequestParam(value = "id") int id) {
		logger.debug("billDeleteHandle here!");
		Bill u = new Bill();
		u.setBillId(id);
		u  = billService.findById(id);
		billService.remove(u);
		List<Bill> bills = billService.findAll();
		model.addAttribute("bills", bills);
		return "admin/bill/bill_list";
	}
	
	@RequestMapping(value = "/admin/billEditForm")
	public String billEditFormHandle(Model model,@RequestParam(value = "id") int id) {
		logger.debug("billEditFormHandle here!");
		Bill u = new Bill();
		u.setBillId(id);
		u  = billService.findById(id);
		model.addAttribute("bill", u);
		model.addAttribute("action","billEdit");
		return "admin/bill/bill_form";
	}
	
	@RequestMapping(value = "/admin/billEdit")
	public String billEditHandle(Model model,@ModelAttribute( "Bill" ) @Valid Bill bill) {
		logger.debug("billEditHandle here!");
		
		// set properties 
		Bill u = new Bill();
		u  = billService.findById(bill.getBillId());
		u.setNumber(bill.getNumber());
		u.setName(bill.getName());
		u.setDetail(bill.getDetail());
		bill.setActiveFlg(true);
		//u.setPercentRate(bill.getPercentRate());

		// set User
//		UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//		User user = new User();
//		user.setLogin(userDetails.getUsername());
//		user = userService.findListByCodition(user).get(0);
//		u.setUser(user);
		
		billService.merge(u);
		u = new Bill();
		u.setBillId(bill.getBillId());
		List<Bill> bills = billService.findAll();
		model.addAttribute("bills", bills);
		return "admin/bill/bill_list";
	}
	
	
	@RequestMapping(value = "/admin/billAddForm")
	public String billAddFormHandle(Model model) {
		logger.debug("billAddFormHandle here!");
		List<Bill> bills = billService.findAll();
		model.addAttribute("action","billAdd");
		model.addAttribute("bills",bills);
		return "admin/bill/bill_form";
	}
	
	@RequestMapping(value = "/admin/billAdd")
	public String billAddHandle(Model model,@ModelAttribute( "Bill" ) @Valid Bill bill,@RequestParam(value = "billId") int billId) {
		logger.debug("billEditHandle here!");
		bill.setActiveFlg(true);
		
		// set Bill
		Bill r =billService.findById(billId);
		
		// set User
//		UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//		User user = new User();
//		user.setLogin(userDetails.getUsername());
//		user = userService.findListByCodition(user).get(0);
//		r.setUser(user);
//		
		billService.persist(r);
		List<Bill> bills = billService.findAll();
		model.addAttribute("bills", bills);
		return "admin/bill/bill_list";
	}
	
	
	@RequestMapping(value = "/admin/createBillByNumberSummary")
	public String createBillByNumberSummaryHandle(Model model,HttpServletRequest req) {
		logger.debug("createBillByNumberSummaryHandle here!");
		Calendar cal = Calendar.getInstance();
		String dateExport  = dateFormat.format(cal.getTime());
		Map<String,Integer> percen = NumberUnity.setPercen();
		//find all data before summary
		List<Number> numberAll = numberService.findAll();
		// get total price for all type
		Map<String,Integer> totals =  numberService.getNumberSummaryTotal(numberAll);
		// logic summary Number to List 
		Map<String,Map<String,Integer>> numbers = numberService.numberSummary(numberAll);
		// print summary data
		NumberUnity.printMap(numbers);
		// Get rule for budget
		List<Rule> ruleAll = ruleService.findAll();
		
		System.out.print(totals);
		
		model.addAttribute("totals", totals);
		model.addAttribute("numbers", numbers);
		model.addAttribute("percen", percen);
		model.addAttribute("rule", ruleAll.get(0));
		model.addAttribute("dateExport", dateExport);
		model.addAttribute("limitTop", req.getParameter("limitTop"));
		model.addAttribute("limitDown", req.getParameter("limitDown"));
		return "admin/bill/bill_create_form";
	}
	
		//addPeriod
		@RequestMapping(value = "/admin/addBill")
		public String addBillHandle(Model model,@RequestParam(value = "inNumber") String inNumber,@RequestParam(value = "outNumber") String outNumber) {
			logger.debug("addBillHandle here!");
			
			String inNumberText = inNumber.toString().replaceAll("\\r", " ").replaceAll("\\n", " ");
			String outNumberText = outNumber.toString().replaceAll("\\r", " ").replaceAll("\\n", " ");
			
			
			// Call service for Transaction rollback 
			
			// Create Bill
			
			// create period
			
			// remove all number finish with period
			
			
			List<Bill> bills = billService.findAll();
			model.addAttribute("bills", bills);
			return "admin/bill/bill_list";
		}
		
		@RequestMapping(value = "/admin/detailBill")
		public String detailBillFormHandle(Model model,@RequestParam(value = "id") int id) {
			logger.debug("detailBillFormHandle here!");
			Bill u = new Bill();
			u.setBillId(id);
			u  = billService.findById(id);
			model.addAttribute("bill", u);
			model.addAttribute("action","billEdit");
			return "admin/bill/bill_detail";
		}
	
}
